package com.github.maojx0630.wechat.bot.monitor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.zhxu.okhttps.HTTP;
import cn.zhxu.okhttps.fastjson2.Fastjson2MsgConvertor;
import com.alibaba.fastjson2.JSONObject;
import com.github.maojx0630.wechat.bot.config.WechatConfig;
import com.github.maojx0630.wechat.bot.dto.ImageParam;
import com.github.maojx0630.wechat.bot.dto.TextParam;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author 毛家兴
 * @since 2024-04-17 11:25
 */
@Slf4j
@Component
public class WechatUtil {

  @Getter private final HTTP http;

  public WechatUtil(WechatConfig config) {
    if (StrUtil.isBlank(config.getWechat())) {
      throw new RuntimeException("wechat地址不能为空");
    }
    String string = URLUtil.normalize(config.getWechat());
    if (StrUtil.endWith(string, "/")) {
      string = StrUtil.removeSuffix(string, "/");
    }
    log.info("微信连接地址:{}", string);
    this.http = HTTP.builder().baseUrl(string).addMsgConvertor(new Fastjson2MsgConvertor()).build();
  }

  public void sendText(TextParam param) {
    String json =
        http.sync("/api/sendTxtMsg")
            .addBodyPara("wxid", param.getWxid())
            .addBodyPara("content", param.getContent())
            .addBodyPara("atlist", param.getAtlist())
            .bodyType("json")
            .post()
            .getBody()
            .toString();
    log.info("发送消息结果:{}", json);
  }

  public void sendImage(ImageParam param) {
    String json =
        http.sync("/api/sendImgMsg")
            .addBodyPara("wxid", param.getWxid())
            .addBodyPara("image", param.getImage())
            .addBodyPara("path", param.getPath())
            .bodyType("json")
            .post()
            .getBody()
            .toString();
    log.info("发送消息结果:{}", json);
  }

  public String userInfo() {
    String json = http.sync("/api/userInfo").get().getBody().toString();
    JSONObject obj = JSONObject.parseObject(json);
    JSONObject data = obj.getJSONObject("data");
    return data.getString("accountName");
  }
}
